import component from "../../Component.js"
import SensorUtils from "../SensorUtils.js";
import {LayerType} from "../../../experience/db/Type.js"

const Overlay = ol.Overlay;
const Draw = ol.interaction.Draw;
const Collection = ol.Collection;

export default class PoweredAreaEditor extends component {
    constructor() { super() }

    async control() {
        this.ztreeUtils = new SensorUtils();
        this.drawAreaInteraction = null;
        this.AreaFeatures = new Collection([]);
        // 当前选中的 传感器id
        this.currentSelectGas = null;
        // 当前选中的 断电区域
        this.PAarea = null;
        const DrawArea = $('#pAreaDraw');
        const PointArea = $('#pAreaPoint');
        // 创建 用于 编辑断电区域的 overlay
        const OverlayContainer = document.getElementById('PoweredAreaContainer');
        this.PoweredAreaOverlay = new Overlay({
            element: OverlayContainer,
            autoPan:true,positioning:'center-center'
        });
        this.drawer.map.addOverlay(this.PoweredAreaOverlay);
        // 创建断电区域的对话框
        this.PAdialog = this.CreatePaDialog();
        // 获取所有 断馈电传感器的列表
        const {data:gasNodes} = await this.ztreeUtils.getAllGasNodes();

        // 存储 断馈电 传感器列表
        this.PoweredGasNodes = gasNodes.filter((node) => {
            return node.node_type === '断馈电'
        })
        // 绑定 点击 绘制断电区域的事件回调函数
        DrawArea.on('click',async (e) => {
            const color = DrawArea.css('color');
            if(color === 'rgb(51, 51, 51)') {
                // 未激活状态
                // 1.颜色的切换
                DrawArea.css({'color':'rgb(255,0,0)'});
                // 2.打开绘图交互
                this.drawAreaInteraction = new Draw({
                    source:this.drawer.source(LayerType.SMPoweredArea),
                    type:'Polygon',
                    features:this.AreaFeatures
                })
                this.drawer.map.addInteraction(this.drawAreaInteraction);
            } else {
                // 激活状态
                // 1.颜色的切换
                DrawArea.css({'color':'rgb(51,51,51)'});
                // 2.存储 断电区域
                const AreaFeatures = this.AreaFeatures.getArray();
                const AreaCoordinates = [];
                AreaFeatures.forEach((feature) => {
                    const coordinates = feature.getGeometry().getCoordinates()[0];
                    AreaCoordinates.push(coordinates);
                });

                const unNormalAreaCoordinates = AreaCoordinates.map((area) => {
                    const resources = [];
                    area.forEach((el) => {
                        const x = this.algo.denormalX(el[0]);
                        const y = this.algo.denormalY(el[1]);
                        resources.push([x, y]);
                    });
                    return resources;
                });

                await this.api.addSmPoweredAreas(unNormalAreaCoordinates);
                // 3.关闭 draw交互,并清空 modify图层
                this.drawer.map.removeInteraction(this.drawAreaInteraction);
                this.drawer.source(LayerType.Modify).clear();
                // 4.更新 断电区域的图层
                await this.drawer._safeMonitorPowerArea();
                // 5.清空 this.AreaFeatures
                this.AreaFeatures = new Collection([]);
            }
        });

        this.emitter.on('send-powered-area',() => {
            const powered_area_feature = this.emitter.params[0]
            // 在断电区域选择器激活的状态下  要执行的进行响应的函数
            this.SelectPAReflect(powered_area_feature)
        })

        // 绑定 点击 选中断电区域的事件回调函数
        PointArea.on('click',(e) => {
            // 1.颜色的切换
            const color = PointArea.css('color');
            if(color === 'rgb(51, 51, 51)') {
                // 未激活状态
                PointArea.css({'color':'rgb(255,0,0)'});
                localStorage.setItem('PA_select_status', true);
            } else {
                // 激活状态
                PointArea.css({'color':'rgb(51,51,51)'})
                localStorage.setItem('PA_select_status', false);
                // 清除 overlay
                this.PoweredAreaOverlay.setPosition(undefined)
            }
        })

        // 绑定 断电区域的设置和删除按钮
        $('#pa_edit_button').on('click',(e) => {
            // 1.首先触发 弹窗，弹窗的功能是去将该断电区域与相关的传感器进行关联。
            this.PAdialog.open();
            // 2. 将弹窗内部的select标签内的option 根据请求得到的传感器列表 进行更新
            let optionHtml = '';
            this.PoweredGasNodes.forEach((gas) => {
                optionHtml += `<option value="${gas.node_id}">${gas.name}</option>`;
            });
            if(this.PoweredGasNodes.length > 0) {
                // 当前选中的 断馈电传感器
                this.currentSelectGas = this.PoweredGasNodes[0].node_id;
            }
            const selector = $('#SensorSelector');
            selector[0].innerHTML = optionHtml;
            selector.on('change',(e) => this.currentSelectGas = e.target.value);
        })

        $('#pa_delete_button').on('click',() => {
            this.app.dialog.confirm('确定删除区域？',() => this.DeletePoweredArea());
        });
    }

    template() {
        const overlay = `
            <div id="PoweredAreaContainer">
                <button id="pa_edit_button" class="PoweredAreaInnerButton PAInnerEditButton">设置</button>
                <button id="pa_delete_button" class="PoweredAreaInnerButton PAInnerDeleteButton">删除</button>
            </div>
        `;
        const dialog = `
            <div id="PoweredAreaDialog" style="width: 400px; height: 400px; background-color: red">       
            </div>
        `;
        this.$$("#article").append(overlay);
        this.$$("#article").append(dialog);
    }

    SelectPAReflect(PA_feature) {
        const PolygonCoordinates = PA_feature.getGeometry().getCoordinates();
        // 计算 polygon的中心坐标
        const center = this.ComputePolygonCenterPosition(PolygonCoordinates[0]);
        this.PoweredAreaOverlay.setPosition(center);
        this.PAarea = PA_feature.get('id');
    }

    // 计算多边形的相对
    ComputePolygonCenterPosition(PolygonCoordinates) {
        //获取一个坐标数组的边界，格式为[minx,miny,maxx,maxy]
        const extent = ol.extent.boundingExtent(PolygonCoordinates);
        //获取边界区域的中心位置
        return ol.extent.getCenter(extent);
    }

    // 创建 断电区域的dialog
    CreatePaDialog() {
        return this.app.dialog.create({
            title: '关联断电馈电传感器',
            cssClass: 'PAdialog',
            content: `
                <div class="PaDialogInnerBox">
                    <select id="SensorSelector" style="width: 100%;height: 30px;margin: 5px auto;">
                        <option value="default" selected>从列表中选择</option>
                    <select/>
                </div>
            `,
            buttons: [{
                text: '关闭'
            }, {
                text: '保存',
                onClick: async () => {
                    await this.submitPoweredAreaRelation();
                }
            }],
        });
    };

    // 点击 保存按钮
    async submitPoweredAreaRelation() {
        await this.api.updateSmPoweredArea(this.PAarea, this.currentSelectGas);
    }

    // 删除 区域
    async DeletePoweredArea() {
        await this.api.deleteSmPoweredArea(this.PAarea);
        // 重置 断电区域的overlay
        this.PoweredAreaOverlay.setPosition(undefined)
        // 更新 断电区域的图层
        await this.drawer._safeMonitorPowerArea();
    }

}

